﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunny.UI;
using System.IO;
using System.Reflection;
using HYI.SDBSERVER;

namespace mySUI
{
    public partial class Form1 : Form
    {
        public DBSERVER myADO ;
        List<string> mylist = new List<string>();

        public string sUserNo = string.Empty; //用户编号
        public string sUserName = string.Empty;//用户姓名
        public string sSiteNo = string.Empty;//客户编号
        public string srole_id = string.Empty;//用户角色

        public Form1()
        {
            InitializeComponent();
        }

        private void doLoadPNG()
        {
            //载入PNG图片
            imageList1.Images.Clear();
            mylist.Clear();

            string path = System.Environment.CurrentDirectory + "\\image";
            if (!Directory.Exists(path))//判断是否存在
            {
                return;
            }

            //文件后缀
            string hz = "PNG";
            DirectoryInfo di = new DirectoryInfo(path);
            //找到该目录下的文件 
            FileInfo[] fi = di.GetFiles();
            //把FileInfo[]数组转换为List    
            List<FileInfo> list = new List<FileInfo>();

            for (int i = 0; i < fi.Length; i++)
            {
                string filestr = fi[i].Name.ToUpper();
                if ((filestr.Substring(filestr.LastIndexOf(".") + 1)) == hz)
                {
                    mylist.Add(filestr);
                    filestr = path + "\\" + filestr;
                    imageList1.Images.Add(Image.FromFile(filestr));
                }
            }
        }

        private void doSetBar()
        {
            //取所有菜单项的语句，如果有权限限制等情况自行修改
            doLoadPNG();

            //取得菜单项数据集
            String SQL1 = "select a.fMenuId,fMenuCaption,fParentId,fPackage,fDataModule,fFormName,fFormParams "
                + " from sys_menu a,sys_groupmenu b"
                + " where b.role_id="+srole_id
                + " and b.fMenuId=a.fMenuId and fVisible=1 order by fParentId,fSeqNo ";
            DataTable myHead = myADO.query(SQL1);

            //1.第一级菜单
            DataRow[] drHead = myHead.Select("fParentId ='0'");
            for (int i = 0; i < drHead.Length; i++)
            {
                int pageIndex = 1000;
                TreeNode parent = Aside.CreateNode(drHead[i]["fMenuCaption"].ToString(), 61451, 24, pageIndex);
                parent.Tag = "";

                string sImage = "0.PNG";
                int iImage = mylist.FindIndex(x => x == sImage);

                //2.第二级菜单
                DataRow[] drItem = myHead.Select("fParentId ='" + drHead[i]["fMenuId"].ToString() + "'");
                for (int j = 0; j < drItem.Length; j++)
                {
                    TreeNode mychildNode = new System.Windows.Forms.TreeNode(drItem[j]["fMenuCaption"].ToString());
                    mychildNode.Tag = drItem[j]["fPackage"].ToString() + ';' + drItem[j]["fFormName"].ToString() + ';' + drItem[j]["fFormParams"].ToString() + ';' + drItem[j]["fMenuId"].ToString();
                    parent.Nodes.Add(mychildNode);
                }

                Aside.SetNodeTipsText(parent.Nodes[0], "1");
            }

        }

        private void Aside_MenuItemClick(TreeNode node, Sunny.UI.NavMenuItem item, int pageIndex)
        {
            //MessageBox.Show(node.Text);
            string myTag = node.Tag.ToString();
            Console.WriteLine(myTag);

            if (myTag == "")
            {
                Console.WriteLine("走...");
                return;
            }

            try
            {
                //tag属性在这里有用到。
                string acName = node.Tag.ToString();
                string acCaption = node.Text.ToString();

                if (acName != "")
                {
                    string[] strArray = acName.Split(new char[] { ';' });
                    if (strArray.Length == 0)
                    {
                    }
                    else
                    {
                        if (strArray[0].Equals("") || strArray[0]== string.Empty)
                        {
                            Console.WriteLine("没有定义dll");
                            return;
                        }

                        String sDLL = strArray[0] + ".dll";
                        String sForm = strArray[0] + "." + strArray[1];
                        String sFormPara = strArray[2];
                        String sMainPara = "300001;"+strArray[3];
                        //MessageBox.Show(sDLL + "--"+ sForm);

                        //判断是否已创建过  
                        for (int i = 0; i < uiTabControl1.TabCount ; i++)
                        {
                            if (uiTabControl1.TabPages[i].Tag.ToString() == myTag)
                            {
                                uiTabControl1.SelectedTab = uiTabControl1.TabPages[i];
                                Console.WriteLine("定...");
                                return;
                            }
                        }
                        
                        //string windowsPath = Path.Combine(Application.StartupPath, "dll");
                        string windowsPath = Path.Combine(Application.StartupPath, "");
                        sDLL = windowsPath + "\\" + sDLL;
                        if (!File.Exists(sDLL))//判断是否存在
                        {
                            this.ShowWarningDialog(sDLL+"文件不存在");
                            return;
                        }
                        Assembly ass = Assembly.LoadFile(sDLL);
                        Type tp = ass.GetType(sForm);  //获取类名，必须 命名空间+类名
                        Object obj = Activator.CreateInstance(tp);  //建立实例
                        MethodInfo meth = tp.GetMethod("StartMe");  //获取方法
                        int t = Convert.ToInt32(meth.Invoke(obj, new Object[] {sMainPara, sFormPara,sUserNo,myADO}));  //Invoke调用方法

                        //调用DLL内窗体，方法2
                        TabPage tabPage1 = new System.Windows.Forms.TabPage();
                        tabPage1.Text = node.Text;
                        tabPage1.Tag = myTag;

                        Form subForm = (Form)ass.CreateInstance(sForm);  //加载Dll中的一个窗体.
                        subForm.Dock = DockStyle.Fill;
                        subForm.FormBorderStyle = FormBorderStyle.None;
                        subForm.TopLevel = false; //在这里一定要注意  否则是加载不出来的
                        tabPage1.Controls.Add(subForm);

                        uiTabControl1.TabPages.Add(tabPage1);
                        uiTabControl1.SelectedTab = tabPage1;

                        subForm.Visible = true;
                    }
                }
            }
            catch (Exception exception)
            {
                this.ShowWarningDialog("载入错误:" + exception.Message);
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Top = 0;
            this.Left = 0;
            Rectangle rect = Screen.GetWorkingArea(this);
            this.Width = rect.Width;
            this.Height = rect.Height;

            //载入图片
            string str = System.Environment.CurrentDirectory + "\\image\\index.png";
            if (File.Exists(str))
            {
                try
                {
                    this.pictureBox1.Image = Image.FromFile(str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            //uiLogo1
            str = System.Environment.CurrentDirectory + "\\image\\logo.png";
            if (File.Exists(str))
            {
                try
                {
                    this.uiLogo1.Image = Image.FromFile(str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            //uiAvatar
            str = System.Environment.CurrentDirectory + "\\image\\退出.png";
            if (File.Exists(str))
            {
                try
                {
                    this.uiAvatar.Image = Image.FromFile(str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            uiusername.Text = sUserName;
            uiusername.Left = uiAvatar.Left - uiusername.Width - 20;

            //初始化
            DBCache myCache = new DBCache();
            myCache.doCache();

            doSetBar();
        }

        private void uiAvatar_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog("确定离开吗?"))
            {
                //关闭界面
                Application.ExitThread();
            }
        }

        private bool uiTabControl1_BeforeRemoveTabPage(object sender, int index)
        {
            //首页不能删除
            bool iDelete = true;
            if (index == 0)
            {
                iDelete=false;
            }

            return iDelete;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.ShowAskDialog("确定离开吗?"))
            {
                //关闭界面
                e.Cancel = false;
                Application.ExitThread();
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
